package dw.fastfile.common.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author : XiaoBai
 * @date : 2022/9/16 11:22
 */
public class ExcelExportUtil {

    /**
     * 文件导出
     *
     * @param objects   结果集
     * @param clazz     映射对象
     * @param fileName  文件名称
     * @param sheetName sheet名称
     * @param response  响应体
     * @throws IOException IO异常
     */
    public static void exportExcel(List<?> objects, Class clazz, String fileName,
                                   String sheetName, HttpServletResponse response) throws IOException {

        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");

        // 设置防止中文名乱码
        String exportName = URLEncoder.encode(fileName, "utf-8");
//        String sheetSubName = URLEncoder.encode(sheetName, "utf-8");

        // 文件下载方式(附件下载还是在当前浏览器打开)
        response.setHeader("Content-disposition", "attachment;filename=" +
                exportName + ".xlsx");

        // 向Excel中写入数据
        EasyExcel.write(response.getOutputStream(), clazz)
                .sheet(sheetName)
                .doWrite(objects);

    }


    /**
     * 文件导出-忽略字段
     *
     * @param objects
     * @param clazz
     * @param fileName
     * @param sheetName
     * @param response
     * @param excludeColumns
     * @throws IOException
     */
    public static void exportExcel(List<?> objects, Class clazz, String fileName,
                                   String sheetName, HttpServletResponse response, Set<String> excludeColumns) throws IOException {

        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");

        // 设置防止中文名乱码
        String exportName = URLEncoder.encode(fileName, "utf-8");
//        String sheetSubName = URLEncoder.encode(sheetName, "utf-8");

        // 文件下载方式(附件下载还是在当前浏览器打开)
        response.setHeader("Content-disposition", "attachment;filename=" +
                exportName + ".xlsx");

        // 向Excel中写入数据
        EasyExcel.write(response.getOutputStream(), clazz).excludeColumnFiledNames(excludeColumns)
                .sheet(sheetName)
                .doWrite(objects);

    }


    /**
     * 多sheet导出
     *
     * @param fileName 文件名称
     * @param map      结果集map
     */
    public static void exportMoreSheetExcel(String fileName, Map<Class, List> map) {
        // 指定文件，自定义列宽，注册样式
        ExcelWriter excelWriter = null;
        try {
            excelWriter = EasyExcel.write(fileName).build();
            int i = 0;
            for (Class c : map.keySet()) {
                WriteSheet writeSheet = EasyExcel.writerSheet(i++, c.getSimpleName()).head(c).build();
                excelWriter.write(map.get(c), writeSheet);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //这一步很关键，不然文件会损坏
            assert excelWriter != null;
            excelWriter.finish();
        }

    }

    /**
     * 多sheet导出
     *
     * @param fileName 文件名称
     * @param clazz    excel文件名
     */
    public static void exportData(String fileName, Map<String, List> param, Class clazz, HttpServletResponse resp) throws IOException {
        OutputStream outputStream = null;
        outputStream = resp.getOutputStream();
        ExcelWriter writer = EasyExcel.write(outputStream).build();
        //开始分批查询分次写入
        int i = 0;
        for (String para : param.keySet()) {
            WriteSheet sheet0 = EasyExcel.writerSheet(i++, para).head(clazz).build();
            List<?> bonusCollect = param.get(para);
            writer.write(bonusCollect, sheet0);
        }
        // 下载EXCEL
        resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        resp.setCharacterEncoding("utf-8");
        String fileNames = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        resp.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileNames + ".xlsx");
        writer.finish();
        outputStream.flush();
        if (outputStream != null) {
            outputStream.close();
        }

    }

}
